import json
import os
import subprocess
import threading
import time
import tkinter as tk
import tkinter.font as tkFont
import webbrowser
import zipfile
from tkinter import messagebox

import psutil
import pyautogui as pyautogui
import pyperclip
import requests

print('欢迎使用Scmd一键安装器。\n正在联网获取最新版本中，请稍后....')
# 获取下载地址链接
resp = requests.get('https://www.scmd.cc/code.json')
data = json.loads(resp.text)


class App:
    def __init__(self, root):
        print('获取成功。\n最新版本为V'+data['version']+'\n正在等待用户点击安装....')
        root.title(r"Scmd一键安装器V" + data['version'])
        width = 300
        height = 200
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        GLabel_589 = tk.Button(root)
        GLabel_589["bg"] = "#1e9fff"
        ft = tkFont.Font(family='Times', size=10)
        GLabel_589["font"] = ft
        GLabel_589["fg"] = "#ffffff"
        GLabel_589["justify"] = "center"
        GLabel_589["relief"] = "flat"
        GLabel_589["text"] = "网站：" + data['home'] + "(点击跳转)"
        GLabel_589.place(x=0, y=0, width=300, height=30)
        GLabel_589["command"] = self.GLabel_589

        self.GButton_858 = tk.Button(root)
        self.GButton_858["bg"] = "#5fb878"
        self.GButton_858["disabledforeground"] = "#009688"
        ft = tkFont.Font(family='Times', size=18)
        self.GButton_858["font"] = ft
        self.GButton_858["fg"] = "#ffffff"
        self.GButton_858["justify"] = "center"
        self.GButton_858["text"] = "安装"
        self.GButton_858["relief"] = "flat"
        self.GButton_858.place(x=90, y=60, width=125, height=50)
        self.GButton_858["command"] = self.GButton_858_command

        GLabel_900 = tk.Button(root)
        GLabel_900["bg"] = "#999999"
        ft = tkFont.Font(family='Times', size=10)
        GLabel_900["font"] = ft
        GLabel_900["fg"] = "#ffffff"
        GLabel_900["justify"] = "center"
        GLabel_900["relief"] = "flat"
        GLabel_900["text"] = data['text'] + data['cmd'] + "(点我复制)"
        GLabel_900.place(x=0, y=140, width=300, height=30)
        GLabel_900["command"] = self.GLabel_900

        GLabel_418 = tk.Button(root)
        GLabel_418["bg"] = "#00ced1"
        ft = tkFont.Font(family='Times', size=10)
        GLabel_418["font"] = ft
        GLabel_418["fg"] = "#ffffff"
        GLabel_418["justify"] = "center"
        GLabel_418["relief"] = "flat"
        GLabel_418["text"] = data['text2'] + "(点击跳转)"
        GLabel_418.place(x=0, y=170, width=300, height=30)
        GLabel_418["command"] = self.GLabel_418
    def GLabel_900(self):
        pyperclip.copy(data['cmd'])

    def GLabel_589(self):
        webbrowser.open(data['home'])

    def GLabel_418(self):
        webbrowser.open(data['help'])
    def main(self):
        print('开始安装。')
        result = tk.messagebox.showinfo(title='提醒',
                                        message='请打开并登陆steam，安装需要等待csgo打开成功，所以每台电脑用时不同，请耐心等待。')
        if result:
            self.GButton_858['state'] = 'disabled'
            BASE_DIR = os.path.dirname(os.path.abspath(__file__))
            pyautogui.keyDown('win')
            pyautogui.keyDown('r')
            pyautogui.keyUp('win')
            pyautogui.keyUp('r')
            pyperclip.copy('steam://rungameid/730')
            pyautogui.hotkey('ctrl', 'v')
            pyautogui.keyDown('enter')
            pyautogui.keyUp('enter')

            def find_path(name):
                while True:
                    time.sleep(1)
                    print('正在等待CSGO启动中...，如无法启动请手动启动。')
                    for pid in psutil.pids():
                        if psutil.Process(pid).name() == name:
                            return psutil.Process(pid).exe()

            url = find_path('csgo.exe')[:-8] + 'csgo\cfg'
            keyfile = requests.get(data['url'])
            open(BASE_DIR + '\latest.zip', 'wb').write(keyfile.content)
            zip_file = zipfile.ZipFile(BASE_DIR + '\latest.zip')
            zip_list = zip_file.namelist()
            for index, i in enumerate(zip_list):
                if i.count('txt'):
                    del zip_list[index]
            for f in zip_list:
                zip_file.extract(f, url)
            zip_file.close()
            subprocess.Popen('taskkill /F /IM csgo.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
            tk.messagebox.showinfo(title='安装成功',
                                   message='安装成功！请打开游戏，在控制台输入' + data['cmd'] + ' 即可使用！')
            print('安装完成。')

        else:
            return
    def GButton_858_command(self):
        T = threading.Thread(target=self.main, args=())
        T.start()


if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
